package com.mes.inventory.dao;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Repository;

import com.bstek.dorado.data.entity.EntityUtils;
import com.bstek.dorado.data.provider.Page;
import com.mes.basicdata.domain.Operation;
import com.mes.common.dao.BasicDao;
import com.mes.inventory.dao.iface.IInvCheckDetailDao;
import com.mes.inventory.domain.InvCheckDetail;
@Repository
public class InvCheckDetailDao extends BasicDao<InvCheckDetail> implements IInvCheckDetailDao{
	public void saveInvCheckDetail(Set<InvCheckDetail> invCheckDetails) throws Exception {
		for (InvCheckDetail i : invCheckDetails) {
			switch (EntityUtils.getState(i)) {
			case MODIFIED:
				this.update(i);
				break;
			case DELETED:
				this.delete(i);
				break;
			case NEW:
				this.add(i);
				break;
			default:
				break;
			}
		}
	}

	@Override
	public void getInvCheckDetails(Page<InvCheckDetail> page, Map<String, Object> parameter) throws Exception {
		// TODO Auto-generated method stub
		Map<String, Object> args = new HashMap<String, Object>();
		StringBuffer coreHql = new StringBuffer("from "
				+ InvCheckDetail.class.getName() + " a where 1=1 ");

		String warehouseUid = (String) parameter.get("warehouseUid");
		if (StringUtils.isNotEmpty(warehouseUid)) {
			coreHql.append(" and a.warehouseUid = :warehouseUid ");
			args.put("warehouseUid",warehouseUid);
		}
		String invCheckUid = (String) parameter.get("invCheckUid");
		if (StringUtils.isNotEmpty(invCheckUid)) {
			coreHql.append(" and a.invCheckUid = :invCheckUid ");
			args.put("invCheckUid",invCheckUid);
		}
		
		String countHql = "select count(*) " + coreHql.toString();
		String hql = coreHql.toString();
		
		Map<String, Object> newArgs = new HashMap<String, Object>();
		String key;
		String newKey;
		Iterator<String> iterator = args.keySet().iterator();
		while(iterator.hasNext()){
			key = (String)iterator.next();
			newKey = key.replace(".", "_");
			newArgs.put(newKey, args.get(key));
			hql = hql.replace(":"+key, ":"+newKey);
			countHql = countHql.replace(":"+key, ":"+newKey);
			
			System.out.println("hql: " + hql);
			System.out.println("countHql: " + countHql);
			System.out.println("newArgs: " + newArgs);
		}
		this.pagingQuery(page, hql, countHql, newArgs);
		
	}	
}
